<template>
  <div class="content" >
    <div class="box" >
        <div class="logo" ><img src="@/assets/img/icon/logo.png" alt="qingyang"></div>
        <div class="title" >专业的云端个人空间</div>
        <div class="form" >
          <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="0px" class="demo-ruleForm">
            <el-form-item prop="number">
              <el-input prefix-icon="el-icon-user" placeholder="请输入账号" v-model.number="ruleForm.number"></el-input>
            </el-form-item>
            <el-form-item prop="pass">
              <el-input prefix-icon="el-icon-lock" placeholder="至少8~32位密码，区分大小写" type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item prop="checkPass">
              <el-input prefix-icon="el-icon-lock" placeholder="确认密码" type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div class="btn" >
          <el-button type="primary" style="width:100%" @click="submitForm('ruleForm')" >注册</el-button>
        </div>
        <div class="otherway" >
          <div @click="loginFun" >使用已有账户登录</div>
        </div>
    </div>
  </div>
</template>
<script>
import {
  reactive,
  toRefs,
  inject
} from "vue";
import { useRouter } from 'vue-router'
// 使用版本为3.0.0-rc1,新版会报错
import { JSEncrypt } from "jsencrypt"
import { ElMessage } from 'element-plus'
import Regular from '@/assets/js/regular'
export default {
  name: "register",
  setup() {
    const state = reactive({});
    const router = useRouter()
    const Request = inject("$Request")
    const Api = inject("$Api")
    const loginFun = ()=> {
      router.push({path:'/login'})
    }
    const register = (number,pass)=> {
      const params = {
        userNumber:number,
        userPassword:pass
      };
      const privateKey = `-----BEGIN PUBLIC KEY-----
      MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDorvAXRx6i5dDhPSbC+SMDKo0f
      FQWoK43y8zIjYPsvwyEMtz0Rd0yqq4kGXeSIO/X7Rcsqvmt2EVCGH/aw3AQt0GQd
      yb4KTEfYsz56JzyYHGi4ubSwsQP2SR4luPg8vQUzusyxuQ2+6wOpKTAD6mOjlJco
      otgGNJu9q1IxtIlqhQIDAQAB
      -----END PUBLIC KEY-----`
      const encryptor = new JSEncrypt()
      encryptor.setPublicKey(privateKey)
      const rsaParams = encryptor.encrypt(JSON.stringify(params))//rsaPassWord 就是得出来的加密串
      Request.requestPost({ rsaParams }, Api.apiUser.register)
        .then((res) => {
          console.log(res)
          if (res.data.code == "0") {
            ElMessage.success('注册成功，请登录~')
            router.push({ path: "/login" });
          } else {
            ElMessage.error(res.data.msg)
          }
        })
        .catch((err) => {
          console.error(err);
        });
    }
    return {
      ...toRefs(state),
      loginFun,
      register
    };
  },
  data() {
    var checkNumber = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('账号不能为空'));
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error('请输入数字值'));
        } else {
          if (value.toString().length<6||value.toString().length>11) {
            callback(new Error('请输入6~11位数字'));
          } else {
            callback();
          }
        }
      }, 1000);
    };
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      }else if((Regular.login_password).test(value) == false){
        callback(new Error('请输入8-32位密码，至少包含字母数字特殊字符中任意2种'));
      }else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.ruleForm.pass) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        number: '',
        pass: '',
        checkPass: ''
      },
      rules: {
        pass: [
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPass: [
          { validator: validatePass2, trigger: 'blur' }
        ],
        number: [
          { validator: checkNumber, trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.register(this.ruleForm.number,this.ruleForm.pass)
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
@import "@/styles/variable.scss";
.content{
  background: url("../../assets/img/bg/login_bg.png");
  background-repeat: no-repeat;
  background-size: 100% 100%;
  width: 100vw;
  height: 100vh;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  .box{
    width: 25vw;
    height: auto;
    display: flex;
    flex-direction: column;
    .logo{
      img{
        height: 42px;
      }
    }
    .title{
      text-align: center;
      color: $gray-weight;
      padding: 16px 0;
    }
    .form{
      padding: 16px 0;
    }
    .btn{
      padding: 8px 0;
    }
    .otherway{
      padding: 8px 0;
      color: $blue-weight;
      cursor: pointer;
    }
  }
}
</style>